import React from 'react'
import { Scrollbars } from 'react-custom-scrollbars'
import { Dropdown, Menu, Tag } from 'antd'
import { HomeOutlined } from '@ant-design/icons'
import classnames from 'classnames'
import { useHistory, useLocation, useModel } from 'umi'
import { HomePath } from '@/common/constants'

const TagList: React.FC = () => {
  const history = useHistory()
  const location = useLocation()
  const { tagList, deleteTag, closeOtherTag, emptyTag, closeRightTags } = useModel('tagsView')
  const { pathname } = location

  const handleClose = (tag: any) => {
    const { path } = tag
    let to = HomePath

    if (path === pathname) {
      // 处理关闭当前标签
      tagList.some((item: any, index: number) => {
        if (item.path === path) {
          to = index < tagList.length - 1 ? tagList[index + 1]?.path : tagList[index - 1]?.path
          return true
        }
        return false
      })

      history.push(to)
    }

    deleteTag(tag)
  }

  const handleClick = (path: string) => {
    history.push(path)
  }

  const onMenu = (e: any, tag: any, index: number) => {
    switch (e.key) {
      case '1':
        closeRightTags(tag.path, index)
        break
      case '2':
        closeOtherTag({ tag })
        break
      case '3':
        emptyTag()
        break
      default:
        console.log('default')
    }
  }

  const menu = (tag: any, index: number) => {
    return (
      <Menu onClick={(e) => onMenu(e, tag, index)}>
        <Menu.Item key="1">关闭右侧</Menu.Item>
        <Menu.Item key="2">关闭其它</Menu.Item>
        <Menu.Item key="3">关闭全部</Menu.Item>
      </Menu>
    )
  }

  return (
    <Scrollbars autoHide autoHideTimeout={1000} autoHideDuration={200} hideTracksWhenNotNeeded>
      <ul className="tags-wrap">
        {tagList.map((tag: any, index: number) => (
          <li
            key={tag.path}
            className={classnames({
              'tag-active': pathname === tag.path,
              'tag-home': HomePath === tag.path,
            })}
          >
            <Dropdown overlay={menu(tag, index)} trigger={['contextMenu']}>
              <Tag
                onClose={() => {
                  handleClose(tag)
                }}
                closable={tag.path !== HomePath}
                onClick={() => {
                  handleClick(tag.path)
                }}
              >
                {tag.path === HomePath ? <HomeOutlined /> : tag.title}
              </Tag>
            </Dropdown>
          </li>
        ))}
      </ul>
    </Scrollbars>
  )
}

export default TagList
